#include "GameEngine/TextureManager.h"

char TextureManager::p_textureNames[MAX_TEXTURE_NAMES][40];
GLuint TextureManager::p_textureIndex[MAX_TEXTURE_NAMES];
unsigned int TextureManager::n_text=0;

static bool isTexManInited=false;

bool TextureManager::init(){
	memset(TextureManager::p_textureNames,0,MAX_TEXTURE_NAMES*40);
	memset(TextureManager::p_textureIndex,INVALID_TEXTURE,MAX_TEXTURE_NAMES);
	if(!TextureManager::p_textureNames || !TextureManager::p_textureIndex)
		return false;
	isTexManInited=true;
	return true;
}

GLuint TextureManager::loadTextureFromFile(const char *fileName){
	if(fileName[0]==0)
		return INVALID_TEXTURE;
	if(!isTexManInited)
		if(!TextureManager::init())
			return INVALID_TEXTURE;
	if(strlen(fileName)>40)
		return INVALID_TEXTURE;

	GLuint tid=findTexture(fileName);
	if(tid != INVALID_TEXTURE)
		return tid;

	if(PVRTTextureLoadFromPVR(fileName, &p_textureIndex[n_text]) != PVR_SUCCESS){
		return INVALID_TEXTURE;
	}
	strcpy(p_textureNames[n_text],fileName);
	n_text++;
	return p_textureIndex[n_text-1];
}

GLuint TextureManager::loadTextureFromPointer(unsigned int *buffer){
	if(!isTexManInited)
		if(!TextureManager::init())
			return INVALID_TEXTURE;
	return INVALID_TEXTURE;
}

GLuint TextureManager::findTexture(const char *fileName){

	if(strlen(fileName)>40)
		return INVALID_TEXTURE;

	for(unsigned int i=0; i<n_text; i++){
		if(fileName[0] != 0 && strcmp(fileName,p_textureNames[i]) == 0){
			return p_textureIndex[i];
		}
	}

	return INVALID_TEXTURE;
}
